<template>
    <div>
        <a-modal
            title="添加需求"
            :bodyStyle="{ height: '600px', overflow: 'hidden' }"
            centered
            v-model:visible="visible"
            :confirm-loading="loading"
            :width="1000"
            okText="保存"
            @ok="handleSave"
            @cancel="handleCancel"
        >
            <flexbox align="flex-start" style="padding-left: 12px">
                <flexbox v-show="searchType === 1">
                    <h-dic-select radio title="项目" :defaultOptions="projectOptions" @change="handleChange($event, 'pro')" v-if="visible" />
                    <h-dic-select :defaultOptions="issueTypeOptions" class="margin-l-8" title="类型" @change="handleChange($event, 'issueType')" />
                    <h-dic-select
                        :defaultOptions="issueStatusOptions"
                        class="margin-l-8"
                        title="状态"
                        @change="handleChange($event, 'issueStatus')"
                    />
                    <a-input
                        class="cell-item margin-l-8"
                        allowClear
                        placeholder="请输入issue名称"
                        v-model:value="form.name"
                        style="min-width: 300px"
                    />
                </flexbox>
                <flexbox v-show="searchType === 2">
                    <a-input
                        class="cell-item margin-l-8"
                        allowClear
                        placeholder="请按照jira语法输入"
                        v-model:value="form.jql"
                        style="min-width: 610px"
                    />
                </flexbox>
                <flexbox v-show="searchType === 3">
                    <a-input
                        class="cell-item margin-l-8"
                        allowClear
                        placeholder="请输入issue关键字"
                        v-model:value="form.issueKey"
                        style="min-width: 610px"
                    />
                </flexbox>
                <flexbox>
                    <a-button type="primary" @click="handleSearch">搜索</a-button>
                    <a-tooltip title="切换到使用JQL的高级搜索" v-if="searchType === 1">
                        <a class="margin-l-8" @click="handleChangeType(2)">高级</a>
                    </a-tooltip>
                    <a-tooltip title="切换到基本搜索" v-else>
                        <a class="margin-l-8" @click="handleChangeType(1)">简单</a>
                    </a-tooltip>
                    <a-tooltip title="切换到issue查询">
                        <a class="margin-l-8" @click="handleChangeType(3)">issue key查询</a>
                    </a-tooltip>
                </flexbox>
            </flexbox>
            <a-divider />
            <CustomTable
                autoResize
                rowKey="id"
                size="small"
                :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                :columns="columns"
                :data-source="list"
                :pagination="paginationConfig"
                @change="handleTableChange"
            />
        </a-modal>
    </div>
</template>

<script lang="ts">
import api from '@/api';
import store from '@/store';
import { message } from 'ant-design-vue/es';
import { CustomTable, HCustomSelect, HDicSelect, HShowMoreSelect, HRangePickerCell } from '@/components';
import { defineComponent, reactive, toRefs } from 'vue';
export default defineComponent({
    components: {
        HCustomSelect,
        HDicSelect,
        HShowMoreSelect,
        HRangePickerCell,
        CustomTable
    },
    emits: ['success'],
    setup(props, { emit }) {
        const columns = [
            {
                title: '关键字',
                dataIndex: 'issueKey'
            },
            {
                title: '名称',
                dataIndex: 'summary'
            },
            {
                title: '类型',
                dataIndex: 'issueType'
            },
            {
                title: '状态',
                dataIndex: 'status'
            }
        ];
        const state = reactive<any>({
            form: {
                projectKeyOrId: null,
                issueTypeIds: null,
                issueStatusIds: null,
                jql: '', //输入高级查询方式
                name: '',
                issueKey: ''
            },
            list: [],
            visible: false,
            detail: {},
            type: 1,
            excludeJiraIds: '',
            loading: false,
            searchType: 1,
            selectedRowKeys: [],
            projectOptions: [],
            issueTypeOptions: [],
            issueStatusOptions: [],
            paginationConfig: {
                total: 0,
                pageSize: 20, // 每页中显示10条数据
                showSizeChanger: true,
                pageSizeOptions: ['5', '10', '15', '20'], // 每页中显示的数据
                showTotal: (total: number) => `共有 ${total} 条数据`, // 分页中显示总的数据
                current: 1
            }
        });
        const handleReset = () => {
            state.form = {
                projectKeyOrId: null,
                issueTypeIds: null,
                issueStatusIds: null,
                jql: '', //输入高级查询方式
                name: '',
                issueKey: ''
            };
            state.searchType = 1;
            state.selectedRowKeys = [];
            state.list = [];
        };
        const open = (detail, type) => {
            handleReset();
            state.type = type;
            state.detail = {
                ...detail
            };
            getProjectOptions();
            getIssueTypeOptions();
            getIssueStatusOptions();
            let idArr = [];
            if (state.detail.businessInfos && state.detail.businessInfos.length) {
                const arr = state.detail.businessInfos.map((item) => item.jiraId);
                idArr = idArr.concat(arr);
            }
            if (state.detail.productInfos && state.detail.productInfos.length) {
                const arr = state.detail.productInfos.map((item) => item.jiraId);
                idArr = idArr.concat(arr);
            }
            if (idArr.length) {
                state.excludeJiraIds = idArr.join(',');
            } else {
                state.excludeJiraIds = '';
            }
            getList();
            state.visible = true;
        };
        const handleSave = async () => {
            if (!state.selectedRowKeys.length) {
                message.error('请勿提交空数据');
                return;
            }
            state.loading = true;
            const jiraIds: any = state.selectedRowKeys.join(',');
            const query = {
                jiraIds,
                type: state.type,
                status: null,
                systemId: state.detail.systemId,
                systemReportId: state.detail.id
            };

            const { success, errorMsg } = await api.systemReportModel.saveInfoFromJira(query);
            if (success) {
                state.visible = false;
                message.success('添加成功');
                emit('success');
            } else {
                message.error(errorMsg);
            }
            state.loading = false;
        };
        const handleCancel = () => {
            state.visible = false;
        };
        const onSelectChange = (selectedRowKeys) => {
            state.selectedRowKeys = selectedRowKeys;
        };
        const getProjectOptions = async () => {
            const query = {
                systemId: state.detail.systemId
            };
            const { success, moule } = await api.jiraModel.getAllProjectsFromJira(query);
            if (success) {
                state.projectKeyOrId = null;
                state.projectOptions = [...moule];
            }
        };
        const getIssueTypeOptions = async () => {
            const query = {
                systemId: state.detail.systemId,
                projectKeyOrId: state.form.projectKeyOrId
            };
            const { success, moule } = await api.jiraModel.getIssueTypesFromJira(query);
            if (success) {
                state.form.issueTypeIds = null;
                // 过滤测试issue类型
                state.issueTypeOptions = moule.filter((item) => item.name !== '测试');
            }
        };
        const getIssueStatusOptions = async () => {
            const query = {
                systemId: state.detail.systemId,
                projectKeyOrId: state.form.projectKeyOrId,
                issueTypeIds: state.form.issueTypeIds
            };
            const { success, moule } = await api.jiraModel.getIssueStatusesFromJira(query);
            if (success) {
                state.issueStatusOptions = [...moule];
            }
        };
        const getList = async () => {
            const { current, pageSize } = state.paginationConfig;
            console.log(state.detail);
            const query = {
                empId: store.getters.userInfo.employeeDTO.empId,
                systemId: state.detail.systemId || state.detail.system,
                excludeJiraIds: state.excludeJiraIds,
                ...state.form,
                pageSize,
                pageNum: current
            };
            const { success, moule, errorMsg, totalCount } = await api.jiraModel.getIssuesByConditions(query);
            if (success) {
                // 过滤测试issue类型
                state.list = moule.filter((item) => item.issueType !== '测试');
                state.paginationConfig.total = totalCount;
            } else {
                message.error(errorMsg);
            }
        };
        const handleChange = (val, field) => {
            if (field === 'pro') {
                state.form.projectKeyOrId = val ? val.id : null;
                getIssueTypeOptions();
                getIssueStatusOptions();
            }
            if (field == 'issueType') {
                state.form.issueTypeIds = val;
                state.form.issueStatusIds = null;
                getIssueStatusOptions();
            }
            if (field === 'issueStatus') {
                state.form.issueStatusIds = val;
            }
            handleSearch();
        };
        const handleChangeType = (type) => {
            state.searchType = type;
        };

        const handleTableChange = (val) => {
            state.paginationConfig = val;
            getList();
        };

        const handleSearch = () => {
            state.paginationConfig.current = 1;
            getList();
        };

        return {
            columns,
            ...toRefs(state),
            open,
            handleSave,
            handleCancel,
            onSelectChange,
            getProjectOptions,
            handleChange,
            getList,
            handleSearch,
            handleChangeType,
            handleTableChange
        };
    }
});
</script>

<style scoped lang="less">
.cell-item {
    font-size: 14px;
    cursor: pointer;
    color: #344563;
    margin-right: 8px;
}
::v-deep(.ant-table-body) {
    max-height: 405px !important;
}
</style>